import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch } from 'antd'
import axios from 'axios'
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import UserForm from '../../../components/user-manage/UserForm'
const { confirm } = Modal

export default function UserList() {
  //  存储当前用户列表
  const [dataSource, setdataSource] = useState([])

  // 控制添加modal框，是否显示
  const [isAddVisible, setisAddVisible] = useState(false)

  // 控制更新用户是否显示
  const [isUpdateVisible, setisUpdateVisible] = useState(false)

  // 获取权限列表
  const [roleList, setroleList] = useState([])

  // 获取地区列表
  const [regionList, setregionList] = useState([])

  // 保存当前需要更新的项，以便后面更新页面时，进行setdataSource操作
  const [current, setcurrent] = useState(null)

  // 传递给子组件--UserForm,从而控制，UserForm中，区域是否禁用
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)

  // 添加用户UserForm实例
  const addForm = useRef(null)

  // 更新用户UserForm实例
  const updateForm = useRef(null)

  const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    const roleObj = {
      1: 'superadmin',
      2: 'admin',
      3: 'editor',
    }
    axios.get('/users?_embed=role').then(res => {
      const list = res.data
      setdataSource(
        roleObj[roleId] === 'superadmin'
          ? list
          : [
            // 自己放里面
            ...list.filter(item => item.username === username),
            // 过滤出其余和自己同一权限级别与大洲的的用户
            ...list.filter(
              item =>
                item.region === region && roleObj[item.roleId] === 'editor'
            ),
          ]
      )
    })
  }, [roleId, region, username])

  useEffect(() => {
    axios.get('/regions').then(res => {
      const list = res.data
      setregionList(list)
    })
  }, [])

  useEffect(() => {
    axios.get('/roles').then(res => {
      const list = res.data
      setroleList(list)
    })
  }, [])

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value,
        })),
        {
          text: '全球',
          value: '全球',
        },
      ],

      onFilter: (value, item) => {
        // console.log(item, value)
        if (value === '全球') {
          return item.region === ''
        }
        return item.region === value
      },

      render: region => {
        return <b>{region === '' ? '全球' : region}</b>
      },
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: role => {
        return role?.roleName
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={() => handleChange(item)}
          ></Switch>
        )
      },
    },
    {
      title: '操作',
      render: item => {
        return (
          <div>
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => confirmMethod(item)}
              disabled={item.default}
            />

            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              disabled={item.default}
              onClick={() => handleUpdate(item)}
            />
          </div>
        )
      },
    },
  ]

  //更新用户-事件的回调
  const handleUpdate = item => {
    /* 是因为：react中状态更新不一定是同步的，导致对话框模块还没显示，也就是表单还没挂载就调用了setFieldsValue，所以报错
      解决：使用async/await和setTimeout。 */
    setTimeout(() => {
      setisUpdateVisible(true)
      if (item.roleId === 1) {
        //禁用
        setisUpdateDisabled(true)
      } else {
        //取消禁用
        setisUpdateDisabled(false)
      }
      updateForm.current.setFieldsValue(item)
    }, 0)

    setcurrent(item)
  }

  // Switch控制用户状态
  const handleChange = item => {
    // console.log(item)
    item.roleState = !item.roleState
    setdataSource([...dataSource])

    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState,
    })
  }

  const confirmMethod = item => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        //   console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        //   console.log('Cancel');
      },
    })
  }
  //删除
  const deleteMethod = item => {
    // console.log(item)
    // 当前页面同步状态 + 后端同步

    setdataSource(dataSource.filter(data => data.id !== item.id))

    axios.delete(`/users/${item.id}`)
  }

  // 添加用户-后的modal回调
  const addFormOK = () => {
    addForm.current
      .validateFields()
      .then(value => {
        // console.log(value)
        //post到后端，生成id，再设置 datasource, 方便后面的删除和更新
        axios.post(`/users`, {
          ...value,
          roleState: true,
          default: false,
        }).then(res => {
          /* 这里之所以这样处理，是因为，res.data中，后端返回的数据，
    不是通过连表查询得到的数据，json-server这个情况下也做不到，
    为了保证页面显示正确，我们需要特殊处理一哈 */
          // console.log(res.data)
          setdataSource([
            ...dataSource,
            {
              ...res.data,
              role: roleList.filter(item => item.id === value.roleId)[0],
            },
          ])
        })

        //清空form
        addForm.current.resetFields()

        setisAddVisible(false)
      })
      .catch(err => {
        console.log(err)
      })
  }

  // 更新用户-后的modal回调
  const updateFormOK = () => {
    updateForm.current.validateFields().then(value => {
      // console.log(value)
      setisUpdateVisible(false)

      setdataSource(
        dataSource.map(item => {
          if (item.id === current.id) {
            return {
              ...item,
              ...value,
              role: roleList.filter(data => data.id === value.roleId)[0],
            }
          }
          return item
        })
      )
      setisUpdateDisabled(!isUpdateDisabled)

      axios.patch(`/users/${current.id}`, value)
    })
  }

  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setisAddVisible(true)
        }}
      >
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 15,
        }}
        rowKey={item => item.id}
      />

      <Modal
        visible={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false)
          addForm.current.resetFields()
        }}
        onOk={() => addFormOK()}
      >
        <UserForm
          regionList={regionList}
          roleList={roleList}
          ref={addForm}
        ></UserForm>
      </Modal>

      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()}
      >
        <UserForm
          regionList={regionList}
          roleList={roleList}
          ref={updateForm}
          isUpdateDisabled={isUpdateDisabled}
          isUpdate={true}
        ></UserForm>
      </Modal>
    </div>
  )
}
